﻿using IJhbyService;
using JhbyCommon.CommonModel;
using JhbyCommon.JhbyCommon.CommonMethods;
using JhbyHelper;
using JhbyModel.Models;
using JhbyWebApi.Models;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Newtonsoft.Json;
using OfficeOpenXml;
using OfficeOpenXml.Style;
using System;
using System.Collections.Generic;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace JhbyWebApi.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    public class UserController : ControllerBase
    {
       jhbyrbacContext _context = null;
        //注入
        IUserService _userService;
        public UserController(IUserService userService)
        {
            _userService = userService;
        }
      

        /// <summary>
        /// 用户列表
        /// </summary>
        /// <param name="pageIndex"></param>
        /// <param name="DeptId"></param>
        /// <param name="UserType"></param>
        /// <param name="UserName"></param>
        /// <returns></returns>
        [HttpGet]
        [Route("GetList")]
        public string GetList(int pageIndex, int pageSize, int DeptId, string UserName)
        {
            Response response1 = new Response();
            //token验证 
            int verifytokenid = TokenHelper.VerifyToken(HttpContext.Request);
            response1.Code = verifytokenid;
            if (verifytokenid == 0)
            {
                response1.data = _userService.GetList(pageIndex, pageSize, DeptId, UserName);
            }
            else if (verifytokenid == 1)
            {
                response1.message = "访问用户不存在！";
            }
            else if (verifytokenid == 2)
            {
                response1.message = "Token验证失败！";
            }
            else
            {
                response1.message = "账号已经在其他地方登陆！";
            }
            return JsonConvert.SerializeObject(response1);
        }
        /// <summary>
        /// 用户添加/编辑
        /// </summary>
        /// <param name="userinfo"></param>
        /// <returns></returns>
        [HttpPost]
        [Route("Edit")]
        public string Edit([FromHeader] UserModel userinfo)
        {
            //初始化
            var ms = new MemoryStream();
            this.HttpContext.Request.EnableBuffering();
            this.HttpContext.Request.Body.CopyToAsync(ms).GetAwaiter().GetResult();
            var json = System.Text.Encoding.UTF8.GetString(ms.ToArray());
            userinfo = Newtonsoft.Json.JsonConvert.DeserializeObject<UserModel>(json);
            return JsonConvert.SerializeObject(_userService.Edit(userinfo));
        }

        /// <summary>
        /// 角色下拉列表
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        [Route("UserGetList")]
        public string UserGetList()
        {
            return JsonConvert.SerializeObject(_userService.UserGetList());

        }

        ////图片上传
        //[Route("Image")]
        //[HttpPost]
        //public ActionResult UploadImage(IFormFile file)
        //{
        //    try
        //    {
        //        if (file == null)
        //        {
        //            return new ContentResult { ContentType = "application/json;charset=UTF-8", Content = "文件资源为空" };
        //        }
        //        //获取项目的根目录
        //        string rootpath = Path.Combine(Directory.GetCurrentDirectory(), "wwwroot", "upload");
        //        string fileExt = file.FileName.Substring(file.FileName.LastIndexOf('.')); //文件扩展名
        //        long fileSize = file.Length; //获得文件大小，以字节为单位

        //        if (fileSize > 1024 * 1024 * 2) //2M
        //        {
        //            //上传的文件不能大于2M
        //            return new ContentResult { ContentType = "application/json;charset=UTF-8", Content = "上传文件不允许大于2M" };
        //        }

        //        string newFileName = System.Guid.NewGuid().ToString("N") + fileExt; //随机生成新的文件名
        //                                                                            //具体实现网址浏览图片:  根据项目目录(rootpath)下面的Image       把Image发布到IIS 通过IIS网址查看图片
        //        var filePath = rootpath + "\\" + newFileName;//上传文件的完整目录
        //        using (var stream = new FileStream(filePath, FileMode.Create))
        //        {
        //            file.CopyTo(stream);
        //            stream.Flush();
        //        }
        //        return new ContentResult { ContentType = "application/json;charset=UTF-8", Content = newFileName };
        //    }
        //    catch (Exception)
        //    {

        //        throw;
        //    }

        //}
        [Route("Image")]
        [HttpPost]
        public ActionResult UploadImage(IFormFile file)
        {
            FileModel result = new FileModel();
            UploadModel upload = new UploadModel();
            upload.Expand = "jpg";
            String FileFolder = Path.Combine(Directory.GetCurrentDirectory(), "wwwroot", "upload");
            String FileName = DateTime.Now.ToString("MMddHHmmssffff.") + upload.Expand;
            String FilePath = Path.Combine(FileFolder, FileName);
            if (!Directory.Exists(FileFolder)) { Directory.CreateDirectory(FileFolder); }
            using (FileStream fs = System.IO.File.Create(FilePath))
            {
                file.CopyTo(fs);
                fs.Flush();
            }
            result.Url = $"/upload/{FileName}";
            var newFileName = result.Url;
            //return JsonConvert.SerializeObject(result);
            return new ContentResult { ContentType = "multipart/form-data", Content = newFileName };
        }
        /// <summary>
        /// excel导入导出
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        [Route("ExcelExport")]
        public ActionResult ExcelExport(int DeptId, string UserName)
        {

            try
            {
                #region 获取基本数据
                var predic = PredicateBuilder.True<Viewuser>();

                if (DeptId > 0)
                {
                    predic = predic.And(x => x.DeptId == DeptId);
                }
                if (!string.IsNullOrEmpty(UserName))
                {
                    predic = predic.And(x => x.UserName.Contains(UserName));
                }
                var query = _context.Viewuser
                    .Where(x => x.Id != 1)
                    .Where(predic).ToList();
                #endregion 获取基本数据

                #region 将数据导出到临时文件夹

                string newFileName = DateTime.Now.ToString("yyyyMMMMdddd") + System.Guid.NewGuid().ToString("N") + ".xlsx"; //随机生成新的文件名
                string filePath = Path.Combine(Directory.GetCurrentDirectory(), "wwwroot", "用户信息") + newFileName; //临时文件    本地的路径
                UTF8Encoding utf8 = new UTF8Encoding();
                byte[] buffer = utf8.GetBytes(filePath);
                filePath = utf8.GetString(buffer);

                //文件是否存在
                FileInfo file = new FileInfo(filePath);

                using (ExcelPackage package = new ExcelPackage(file))
                {
                    //添加worksheet
                    ExcelWorksheet worksheet = package.Workbook.Worksheets.Add($"sheet1");
                    //添加表头
                    var columnList = new List<string>();
                    columnList.Add("序号");
                    columnList.Add("部门");
                    columnList.Add("姓名");
                    columnList.Add("性别");
                    columnList.Add("出生年月");
                    columnList.Add("手机号");
                    columnList.Add("角色");
                    columnList.Add("状态");
                    for (int i = 0; i < columnList.Count; i++)
                    {
                        worksheet.Cells[1, i + 1].Value = columnList[i];//列头
                        worksheet.Cells[1, i + 1].Style.Fill.PatternType = ExcelFillStyle.Solid;//设置样式类型
                        worksheet.Cells[1, i + 1].Style.Fill.BackgroundColor.SetColor(Color.FromArgb(255, 255, 255));//设置单元格背景色
                        worksheet.Cells[1, i + 1].Style.Border.BorderAround(ExcelBorderStyle.Thin, Color.Black);//设置单元格所有边框
                        worksheet.Cells[1, i + 1].Style.HorizontalAlignment = ExcelHorizontalAlignment.Center;//居中
                    }
                    int row = 2;
                    foreach (var item in query)
                    {
                        //添加数据
                        worksheet.Cells[row, 1].Value = item.Id;//序号
                        worksheet.Cells[row, 1].Style.Border.BorderAround(ExcelBorderStyle.Thin, Color.Black);//设置单元格所有边框
                        worksheet.Cells[row, 1].Style.HorizontalAlignment = ExcelHorizontalAlignment.Center;//居中
                        worksheet.Cells[row, 2].Value = item.DeptName;
                        worksheet.Cells[row, 2].Style.Border.BorderAround(ExcelBorderStyle.Thin, Color.Black);//设置单元格所有边框
                        worksheet.Cells[row, 2].Style.HorizontalAlignment = ExcelHorizontalAlignment.Center;//居中
                        worksheet.Cells[row, 3].Value = item.UserName;
                        worksheet.Cells[row, 3].Style.Border.BorderAround(ExcelBorderStyle.Thin, Color.Black);//设置单元格所有边框
                        worksheet.Cells[row, 3].Style.HorizontalAlignment = ExcelHorizontalAlignment.Center;//居中
                        worksheet.Cells[row, 4].Value = item.Sex == 0 ? "未知" : item.Sex == 1 ? "男" : "女";//操作类型
                        worksheet.Cells[row, 4].Style.Border.BorderAround(ExcelBorderStyle.Thin, Color.Black);//设置单元格所有边框
                        worksheet.Cells[row, 4].Style.HorizontalAlignment = ExcelHorizontalAlignment.Center;//居中
                        worksheet.Cells[row, 5].Value = item.Birthday + "";
                        worksheet.Cells[row, 5].Style.Border.BorderAround(ExcelBorderStyle.Thin, Color.Black);//设置单元格所有边框
                        worksheet.Cells[row, 5].Style.HorizontalAlignment = ExcelHorizontalAlignment.Center;//居中
                        worksheet.Cells[row, 6].Value = item.UserPhone;
                        worksheet.Cells[row, 6].Style.Border.BorderAround(ExcelBorderStyle.Thin, Color.Black);//设置单元格所有边框
                        worksheet.Cells[row, 6].Style.HorizontalAlignment = ExcelHorizontalAlignment.Center;//居中
                        worksheet.Cells[row, 7].Value = item.RoleName;
                        worksheet.Cells[row, 7].Style.Border.BorderAround(ExcelBorderStyle.Thin, Color.Black);//设置单元格所有边框UserStatus
                        worksheet.Cells[row, 7].Style.HorizontalAlignment = ExcelHorizontalAlignment.Center;//居中
 
                        row++;
                    }

                    worksheet.Column(2).Width = 35;
                    worksheet.Column(3).Width = 25;
                    worksheet.Column(6).Width = 30;
                    worksheet.Column(7).Width = 30;
                    worksheet.Column(8).Width = 20;
                    worksheet.Column(9).Width = 20;
                    //保存workbook
                    package.Save();
                }
                using (FileStream fileStream = new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.Read))
                {
                    // 读取文件的 byte[]

                    byte[] bytes = new byte[fileStream.Length];

                    fileStream.Read(bytes, 0, bytes.Length);

                    fileStream.Close();

                    // 把 byte[] 转换成 Stream
                    Stream stream = new MemoryStream(bytes);

                    System.IO.File.Delete(filePath);
                    #endregion 将数据导出到临时文件夹
                    return File(stream, "application/vnd.ms-excel", filePath);

                }
            }
            catch (Exception)
            {

                throw;
            }

            // return new ContentResult { ContentType = "application/json;charset=UTF-8", Content = filePath };

        }

        /// <summary>
        /// 重置密码
        /// </summary>
        /// <param name="Id"></param>
        /// <returns></returns>
        [HttpGet]
        [Route("ResetPassWord")]
        public string ResetPassWord(int Id)
        {
            Response response = new Response();
            var userlist = _context.Userinfo.Where(x => x.Id == Id).FirstOrDefault();
            userlist.UserPassword = Md5Utils.MD5("123456");
            _context.SaveChanges();
            response.Code = 200;
            response.message = "重置密码成功";
            return JsonConvert.SerializeObject(response);

        }

    }
}
